<?php

namespace Admin\Action;

/**
 * ============================================================================
 * MXCMall开源商城
 * 官网地址:http://www.mothink.cn
 * 联系QQ:510858687
 * ============================================================================
 * 商品控制器
 */
class GoodsAction extends BaseAction {

    /**
     * 查看
     */
    public function toView() {
        $this->isLogin();
        $m = D('Admin/Goods');
        if (I('id') > 0) {
            $object = $m->get();
            $this->assign('object', $object);
        } else {
            die("商品不存在!");
        }
        $this->view->display('/goods/view');
    }

    /**
     * 查看
     */
    public function toPenddingView() {
        $this->isLogin();
        $m = D('Admin/Goods');
        if (I('id') > 0) {
            $object = $m->get();
            $this->assign('object', $object);
            //获取商品款式信息
            $m = D('Admin/GoodsCats');
            $this->assign('goodsCatsList', $m->queryByList());
            //获取商品种质信息
//            $m = D('Admin/goodsClassList');
//            $this->assign('goodsClassList', $m->queryByList());
        } else {
            die("商品不存在!");
        }
        $this->view->display('/goods/view_pendding');
    }

    /**
     * 分页查询
     */
    public function index() {
        $this->isLogin();
        $this->checkPrivelege('splb_00');
        //获取地区信息
        $m = D('Admin/Goods');
        $page = $m->queryByPage();
        $pager = new \Think\Page($page['total'], $page['pageSize']); // 实例化分页类 传入总记录数和每页显示的记录数
    
        foreach ($_POST as $key => $value) {
              $pager->parameter[$key] = $value;
        }
         
        $page['pager'] = $pager->show();
       
        $this->assign('Page', $page);
        $this->assign('shopName', I('shopName'));
        $this->assign('goodsName', I('goodsName'));
        $this->assign('areaId1', I('areaId1', 0));
        $this->assign('areaId2', I('areaId2', 0));
        $this->display("/goods/list");
    }
    
    /**
     * 分页查询
     */
    public function goodsFlag() {
        $this->isLogin();
        $this->checkPrivelege('splb_00');
        //获取地区信息
        $m = D('Admin/Goods');
        $page = $m->goodsFlagList();
        $pager = new \Think\Page($page['total'], $page['pageSize']); // 实例化分页类 传入总记录数和每页显示的记录数
        foreach ($_POST as $key => $value) {
              $pager->parameter[$key] = $value;
        }

        $page['pager'] = $pager->show();
        $this->assign('Page', $page);
        $this->assign('shopName', I('shopName'));
        $this->assign('goodsName', I('goodsName'));
        $this->assign('areaId1', I('areaId1', 0));
        $this->assign('areaId2', I('areaId2', 0));
        $this->display("/goods/list_flag");
    }

    /**
     * 分页查询
     */
    public function queryPenddingByPage() {
        $this->isLogin();
        $this->checkPrivelege('spsh_00');
        //获取地区信息
        $m = D('Admin/Goods');
        $page = $m->queryPenddingByPage();
        $pager = new \Think\Page($page['total'], $page['pageSize']); // 实例化分页类 传入总记录数和每页显示的记录数
        $pager->setConfig('header', '个会员');
        foreach ($_POST as $key => $value) {
              $pager->parameter[$key] = $value;
        }


        $page['pager'] = $pager->show();
        $this->assign('Page', $page);
        $this->assign('shopName', I('shopName'));
        $this->assign('goodsName', I('goodsName'));
        $this->assign('areaId1', I('areaId1', 0));
        $this->assign('areaId2', I('areaId2', 0));
        $this->display("/goods/list_pendding");
    }

    /**
     * 列表查询
     */
    public function queryByList() {
        $this->isAjaxLogin();
        $m = D('Admin/Goods');
        $list = $m->queryByList();
        $rs = array();
        $rs['status'] = 1;
        $rs['list'] = $list;
        $this->ajaxReturn($rs);
    }

    /**
     * 列表查询[获取启用的区域信息]
     */
    public function queryShowByList() {
        $this->isAjaxLogin();
        $m = D('Admin/Goods');
        $list = $m->queryShowByList();
        $rs = array();
        $rs['status'] = 1;
        $rs['list'] = $list;
        $this->ajaxReturn($rs);
    }

    /**
     * 修改待审核商品状态
     */
    public function changePenddingGoodsStatus() {
        $this->isAjaxLogin();
        $this->checkAjaxPrivelege('spsh_04');
        $m = D('Admin/Goods');
        $rs = $m->changeGoodsStatus();
        $this->ajaxReturn($rs);
    }

    /**
     * 修改商品状态
     */
    public function changeGoodsStatus() {
        $this->isAjaxLogin();
        $this->checkAjaxPrivelege('splb_04');
        $m = D('Admin/Goods');
        $rs = $m->changeGoodsStatus();
        $this->ajaxReturn($rs);
    }

    /**
     * 获取待审核的商品数量
     */
    public function queryPenddingGoodsNum() {
        $this->isAjaxLogin();
        $m = D('Admin/Goods');
        $rs = $m->queryPenddingGoodsNum();
        $this->ajaxReturn($rs);
    }

    /**
     * 批量设置精品
     */
    public function changeBestStatus() {
        $this->isAjaxLogin();
        $this->checkAjaxPrivelege('splb_04');
        $m = D('Admin/Goods');
        $rs = $m->changeBestStatus();
        $this->ajaxReturn($rs);
    }

    /**
     * 批量设置推荐
     */
    public function changeRecomStatus() {
        $this->isAjaxLogin();
        $this->checkAjaxPrivelege('splb_04');
        $m = D('Admin/Goods');
        $rs = $m->changeRecomStatus();
        $this->ajaxReturn($rs);
    }

    /**
     *  新增商品
     *   * 参考 http://www.yushangcn.com/index.php/Admin/Goods/toView/id/2458.html
     */
    public function addgoods() {
        $this->isLogin();
        //款式
        $m = D('Admin/GoodsCats');
        $catslist = $m->getCatAndChild();
        //种质
        $m = D('Admin/GoodsClass');
        $classlist = $m->getClassAndChild();
        //商店
        $sql = "select shopId,shopSN,shopName  from __PREFIX__shops 
             where  shopStatus=1 and shopFlag=1 ";
        $ShopList = M('shops')->query($sql);

        $this->assign('goodsSn', time());
        $this->assign('Shoplist', $ShopList);
        $this->assign('classlist', $classlist);
        $this->assign('catslist', $catslist);
        $this->display("/goods/addgoodsView");

    }


    public function editgoods() {
      
        $this->isLogin();
        $goodsId = I("id",0);
        if ($goodsId==0) {
            $this->error("未找到商品ID是{$goodsId}");
            exit;
        }
        //款式
        $m = D('Admin/GoodsCats');
        $catslist = $m->getCatAndChild();
        //种质
        $m = D('Admin/GoodsClass');
        $classlist = $m->getClassAndChild();
        //商店
        $sql = "select shopId,shopSN,shopName  from __PREFIX__shops 
             where  shopStatus=1 and shopFlag=1 ";
        $ShopList = M('shops')->query($sql);
        //商品
        $sql = "select shopId,shopSN,shopName  from __PREFIX__shops 
             where  shopStatus=1 and shopFlag=1 ";
        $goods = M("goods")->where(array('goodsId'=>$goodsId))->find();
        $goods['goodsSn'] = str_replace("SN",'',$goods['goodsSn']);
        //
        $goods['goodsContent'] = M("goodsData")->where(array('goodsId'=>$goodsId))->getField('goodsContent');
        $goods['goodsCatId2'] = intval($goods['goodsCatId2']);
        $goods['goodsClassId2'] = intval($goods['goodsClassId2']); //$goods.goodsClassId2
        
        $m_gallery = M('goods_gallerys');   
        $galleryList = $m_gallery->where(array('goodsId'=>$goodsId))->select();

 
 
 

        $this->assign('galleryList', $galleryList);
        $this->assign('goods', $goods);
        $this->assign('Shoplist', $ShopList);
        $this->assign('classlist', $classlist);
        $this->assign('catslist', $catslist);
        $this->assign('nextpage', $_SERVER['HTTP_REFERER']);

        $this->display("/goods/addgoodsView");
        
    }

    /**
     * 搜索编码
     */
    public function querySn($sn='',$goodsId=0) {

        if(isset($_SERVER["HTTP_X_REQUESTED_WITH"]) && strtolower($_SERVER["HTTP_X_REQUESTED_WITH"])=="xmlhttprequest"){ 
            // ajax 请求的处理方式 
            $isAjax = 1;
        }else{ 
            // 正常请求的处理方式 
            $isAjax = 0;
        };
 
        if (false==$sn) { $sn = I("sn",''); } 
        if (false==$goodsId) $goodsId = I("goodsId",'0');
        if (false==$sn || $goodsId==0) {  
                if (false==$isAjax) {return 'false';} else { die('false');}
        }
        $sn = str_replace("SN",'',trim($sn));
        $count = M("goods")->where(array('goodsId'=>array('neq',$goodsId),'goodsSn'=>'SN'.$sn,'goodsStatus'=>1))->count();
 
        if ($count>0) {
             if (false==$isAjax) {return 'occupation';} else { die('occupation');}
        } else {
             if (false==$isAjax) {return 'success';} else { die('success');}
        }
         
    }
    /**
     * 新增商品插入数据
     * 要求 shopId=0 ，0为特殊商店

     * @return [type] [description]
     */
    public function toAddGoods() {
        $this->isAjaxLogin();

        $m = D('Admin/Goods');
        $data = array();
        $data['shopId'] = $shopId= I('shopId');
        $data['goodsName'] = I('goodsName');
        $data['marketPrice'] = I('marketPrice', 0);    //售价
        $data['shopPrice'] = I('shopPrice', 0);    //合作价
        $data['goodsStock'] = I('goodsStock', 1);
        $cat = $m->getCatData(I('catId'));
        $data['goodsCatId1'] = $cat['goodsCatId1'];
        $data['goodsCatId2'] = $cat['goodsCatId2'];
        $class = $m->getClassData(I('classId'));
        $data['goodsClassId1'] = $class['goodsClassId1'];
        $data['goodsClassId2'] = $class['goodsClassId2'];
        $data['isOffline'] = I('isOffline', 0);
        $data['createTime'] = date('Y-m-d H:i:s');
        $goodsSn =  str_replace("SN",'', I('goodsSN', ''));
        $data['goodsSn'] = 'SN'.$goodsSn;
        $data['isSale'] =  I('isSale',0);

        $goodsId = I("goodsId",0);

        $querySnRes = $this->querySn($data['goodsSn'],$goodsId);
        if ($querySnRes=='occupation') {
            $this->error("商品编码被占用");
        }
        $isGoodsVerify = M('sys_configs')->where('fieldCode = "isGoodsVerify"')->getField('fieldValue');
        if ($isGoodsVerify == 0) {
            $data['goodsStatus'] = 1;
        }
 
        $img = array();
        if ($_FILES['goodsFaceImg']['size']>0) {
            $img = $this->uploadImg('goodsFaceImg');

            
            $data['goodsImg'] = htmlspecialchars_decode($img['picBigPath']);
            $data['goodsThumbs'] = htmlspecialchars_decode($img['picThumbPath']);
            
           
        }
        unset($img,$pic,$_FILES['goodsFaceImg']);

        if ($_FILES['goodsImg']) {
                    $config = array(
                        'maxSize' => 0, //上传的文件大小限制 (0-不做限制)
                        'exts' => array('jpg', 'png', 'gif', 'jpeg'), //允许上传的文件后缀
                        'rootPath' => './Upload/', //保存根路径
                        'driver' => 'LOCAL', // 文件上传驱动
                        'subName' => array('date', 'Y-m'),
                        'savePath' => I('dir', 'uploads') . "/"
                    );
                    $upload = new \Think\Upload($config);
                    $upImgs = $upload->upload($_FILES);

            $images = new \Think\Image();
            $gallerys = array();
            foreach ($upImgs as $key => $upImg) {
 
                $savepath = "Upload/" . $upImg['savepath'];
                $images->open('./Upload/' . $upImg['savepath'] .$upImg['savename']);
                $newsavename = str_replace('.', '_big.', $upImg['savename']);
                $vv = $images->thumb(640,640)->save($savepath . $newsavename);
                $gallerys[$key]['goodsImg'] =   htmlspecialchars_decode($savepath.$newsavename,true);
                 
                //
                $newsavename = str_replace('.', '_thumb.', $upImg['savename']);
                $vv = $images->thumb(320,320)->save($savepath. $newsavename);
                $gallerys[$key]['goodsThumbs'] = htmlspecialchars_decode($savepath.$newsavename,true);
 

                unset($rs['pic']);


            }
 
        }
        unset($img,$pic,$_FILES);            
 
        
        foreach ($data as $v) {
            if ($v === '') {
                var_dump($v);
                $rt['code'] = 0;
                $rt['info'] = '请将信息填写完整!';
                $this->error($rt['info']);
            }
        }
        $data['goodsSize'] = I('goodsSize');
        $data['goodsWeight'] = I('goodsWeight');
        $data['goodsVedio'] = I('goodsVedio', '');
        $data['vedioThumb'] = I('vedioThumb', '');
        
        

        $m = M('goods');
        
        if ($goodsId>0) {
            $m->where(array('goodsId'=>$goodsId))->save($data);

            M("GoodsData")->where(array('goodsId'=>$goodsId))->save(array('goodsContent'=>I('goodsContent', '')));
 
        } else {
            $goodsId = $m->add($data);
            $PostGoodsData = array();
            $PostGoodsData['goodsId'] = $goodsId;
            $PostGoodsData['shopId'] = $shopId;
            $PostGoodsData['goodsContent'] = I('goodsContent', '');
       
            M("GoodsData")->add($PostGoodsData);
        }
 

        if ($goodsId === FALSE) {
            $rt['code'] = 0;
            $rt['info'] = 'Error!';
             
            $this->error($rt['info']);
            exit;

        }

        if (!empty($gallerys)) {
            $dataList = array();
            foreach ($gallerys as $v) {
                if ($v['goodsImg']) {
                    $data = array();
                    $data['goodsId'] = $goodsId;
                    $data['shopId'] = $shopId;
                    $data['goodsImg'] = $v['goodsImg'];
                    $data['goodsThumbs'] = $v['goodsImg'];
                    $dataList[] = $data;
                }
            }
             
            $m = M('goods_gallerys');
            $rs = $m->addAll($dataList);
        }


        $data = array();
        $data['goodsId'] = $goodsId;
        $data['shopId'] = $shopId;
        $data['goodsContent'] = I('content');
        $m = M('goods_data');
        $rs = $m->add($data);
        $this->success('操作成功',I('nextpage'));
        
    }

    public function galleryDele() {
        $gId = I("gid",0);

        try{
            $res =M('goods_gallerys')->where(array('id'=>$gId))->delete();
        }catch(Exception $e){
            die($e->getMessage());
        }
        die('success');
    }

 
    public function uploadImg($key) {
        $dir = I('dir', 'uploads') ? I('dir', 'uploads') : 'uploads';
        $config = array(
            'maxSize' => 0, //上传的文件大小限制 (0-不做限制)
            'exts' => array('jpg', 'png', 'gif', 'jpeg'), //允许上传的文件后缀
            'rootPath' => './Upload/', //保存根路径
            'driver' => 'LOCAL', // 文件上传驱动
            'subName' => array('date', 'Y-m'),
            'savePath' => $dir . "/"
        );
        $upload = new \Think\Upload($config);
        $rs = $upload->upload($_FILES);
        $Filedata = key($_FILES);
 
  
        if (!$rs) {
            return $upload->getError();
        } else {
            $images = new \Think\Image();
            $images->open('./Upload/' . $rs[$Filedata]['savepath'] . $rs[$Filedata]['savename']);
            $newsavename = str_replace('.', '_big.', $rs[$Filedata]['savename']);
            $pic  = './Upload/' . $rs[$Filedata]['savepath'] . $newsavename;
            $vv = $images->thumb(640,640)->save($pic);
            $rs['picBigPath'] = str_replace("./Upload","Upload",$pic);
            
            ////
            $newsavename = str_replace('.', '_thumb.', $rs[$Filedata]['savename']);
            $pic = './Upload/' . $rs[$Filedata]['savepath'] . $newsavename;
            $vv = $images->thumb(320,320)->save($pic);
            $rs['picThumbPath'] = str_replace("./Upload","Upload",$pic);
 
            unset($rs['pic']);
            return $rs;
        }
    }
    

}

?>